﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;


public class Character : MonoBehaviour
{
	public SphereCollider find_distance;			//发现半径
    public SphereCollider hate_distance;			//仇恨半径
    [SerializeField]
    private Animator anim;                      	//定义一个寻路半径
    [SerializeField]
    private Pathfinding pathfind;
    [SerializeField]
    private Hate hate;								//仇恨脚本
    [Header("角色控制器")]
    public CharacterController characterController;

    public bool leader = false;							// 当前对象是否为领队
    public bool monster = false;						// 当前对象是否为怪物

	public Overhead canvas;

	public Transform follw_target;					//跟随目标

    public Player_Attr attr;						//角色属性
    //public Char_data data;
    //public Char_data attr;

    public float health{
        get{
            return attr.health;
        }
    }
    public float health_now{
        get{
            return attr.health_now;
        }
    }

    public enum Mon_state
	{
		standby,
		fight,
		backing,
	};
	public Mon_state mon_state;

    private GameObject target;
    [SerializeField]
    private Ani_event ani_event;
    private int use_once_ID;
    [HideInInspector]
    public float radius;
    public Transform skill_pos;
    public Transform hited_pos;

    public delegate void EventHandler(Damage damage);
    public event EventHandler e_hited;
    public event EventHandler e_hiter;
    public event EventHandler e_hiter_end;

    public void be_hited(Damage damage)
    {
        e_hited(damage);
    }
    public void be_hiter_end(Damage damage)
    {
        e_hiter_end(damage);
    }
    public List<Skill>  skill_list = new List<Skill>();


    void Awake () 
	{
		ini_attr();										//初始化属性
		if (!follw_target) 
        {
            follw_target = transform;
        }
	}

	// Use this for initialization
	void Start ()
	{
        use_once_ID = 0;
        if (leader) 
        {
            Gamecontrol.Instance.player_leader = this;
        }
		find_distance.radius = attr.find_distance;			//
        hate_distance.radius = attr.hate_distance;			//
        hate.track_distance = attr.track_distance;			//
        radius = attr.radius;							//

        skill_list.Add( new Skill(this, attr.skill_1) );	//
        skill_list.Add( new Skill(this, attr.skill_2) );	//

        e_hited += hited_listener;					//
        e_hited += canvas.hited;
        e_hiter += hiter_listener;					//
        e_hiter_end += hiter_end_listener;

        canvas.ini(attr.name,attr.health, attr.height);
        pathfind.speed = attr.movespeed;

        if (monster) 
        {
        	ini_moster();
        }
        else
        {
        	ini_brave();	
        }
	}
	
	// Update is called once per frame
	void Update ()
	{
        for (int i = skill_list.Count - 1; i >= 0; i--) 
        {
            skill_list[i].Update();
        }
        // foreach (Skill sk in skill_list) 
        // {
        //     sk.Update();
        // }
        anim.SetBool ("Isruning", ( pathfind.isruning) );
	}

	void FixedUpdate ()
	{
        if (monster) 
        {
            Ai_moster();
        }
        else
        {
            Ai_brave();
        }
	}

    public void get_target()
    {
        target = hate.get_hate(1);
    }

    // 自动使用技能
    public void attack()
    {
        get_target();
        for (int i = skill_list.Count -1; i >= 0 ; i--) 
        {
            if (skill_list[i].ID == use_once_ID) 
            {
                if ( use_skill(skill_list[i],target) )
                {
                    use_once_ID = 0;
                }
                break;
            }
            if (skill_list[i].auto_use) 
            {
                use_skill(skill_list[i], target);
                break;
            }
        }

        // foreach (Skill sk in skill_list) 
        // {
        //     if (sk.ID == use_once_ID) 
        //     {
        //         if ( use_skill(sk,target) )
        //         {
        //             use_once_ID = 0;
        //         }
        //         break;
        //     }
        //     if (sk.auto_use) 
        //     {
        //         use_skill(sk, target);
        //         break;
        //     }
        // }
    }

    public bool use_skill(Skill skill , GameObject hited = null)
    {
        if (hited == null) 
        {
            hited = target;
        }
        if (!skill.useful)
        {
            return false;//技能cd未好
        }

        Character hited_sc = hited.GetComponent<Character>();
        if (Vector3.Distance(transform.position, hited.transform.position)
            -radius-hited_sc.radius  > skill.attack_distance) 
        {
            if (use_once_ID == 0 || use_once_ID == skill.ID)
            {
                pathfind.FindPath(hited.transform.position);
                use_once_ID = skill.ID;
            }
            return false;//距离太远
        }
        Damage dmg = skill.Hit(hited_sc);
        pathfind.stop();
        transform.LookAt(hited.transform);
        ani_event.effect_list.Add(skill.Get_skill_effect(dmg, skill_pos.position,this, hited_sc));
        anim.SetTrigger("Isattack");
        e_hiter(dmg);
        return true;
    }
	private void ini_moster()
    {
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.body,"skeleton_body");
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.head,"skeleton_head");
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.hand_l,"skeleton_hand_l");
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.hand_r,"skeleton_hand_r");
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.leg_l,"skeleton_leg_l");
        GetComponentInChildren<Avater>().Change_avater(Avater_Part.leg_r,"skeleton_Leg_r");
    }
    private void ini_brave()
    {

    }
	private void Ai_moster()
	{
		if (mon_state == Mon_state.backing) 
    	{
            pathfind.FindPath(hate.origin_pos);
    		//判断已经回到原点
    		if (pathfind.isruning) 
    		{
    			mon_state = Mon_state.standby;
    			hate.Clear_hate();
    			attr.health_now = attr.health;
    		}
    	}
    	else if (hate.have_hate) 
    	{
    		mon_state = Mon_state.fight;
    		attack();
    	}
    	else if (mon_state != Mon_state.standby)
    	{
    		mon_state = Mon_state.backing;
    	}
	}

	private void Ai_brave()
	{
        //characterController.SimpleMove(Vector3.zero);
    	if (Gamecontrol.Instance.Moving_direction != Vector3.zero &&(!Gamecontrol.Instance.move_mode||leader) )
    	{ 
            pathfind.FindPath(Gamecontrol.Instance.Moving_direction);
            if (pathfind.isruning) 
            {
                hate.Refresh_origin_pos();
                return;
            }
    	}
        if (hate.have_hate)
    	{
    		attack();
    	}
    	else if (!pathfind.isruning) 
        {
            pathfind.FindPath(follw_target.position);
        }
	}

	private void ini_attr()
	{
		attr = new Player_Attr(1);						//获取角色属性

        // if (monster) 
        // {
        //     attr = new Brave_data(10001);
        // }
        // else
        // {
        //     attr = new Brave_data(10001);
        // }
        
		//Debug.Log("attr，初始化了啊！");
	}
	private void hited_listener(Damage damage)
    {
        attr.health_now -= damage.Hurt;
        attr.health_now = Mathf.Clamp(attr.health_now, 0, attr.health);
    	if (attr.health_now <= 0) 
    	{
    		anim.SetBool("die",true);
    	}
    }

    private void hiter_listener(Damage damage)
    {
        //Debug.Log("是的，我打人了！");
    }
    private void hiter_end_listener(Damage damage)
    {

    }
}
